<!DOCTYPE html>
<html lang="en">
<head>
  <title>Vert.x Circuit Breaker - Vert.x</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Vert.x is a tool-kit for building reactive applications on the JVM." name="description">
  <link href="http://vertx.io/stylesheets/docs.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/stylesheets/font-awesome.min.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/javascripts/styles/rainbow.min.css" media="screen" rel="stylesheet">
  <!-- IE 6-8 support of HTML 5 elements -->
  <!--[if lt IE 9]>
  <script src="http://static.jboss.org/theme/js/libs/html5/pre3.6/html5.min.js"></script>
  <![endif]-->

  <link rel="apple-touch-icon" sizes="57x57" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="http://vertx.io/assets/favicons/vertx-favicon-7/manifest.json">
  <link rel="mask-icon" href="http://vertx.io/assets/favicons/vertx-favicon-7/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#7d3194">
  <meta name="msapplication-TileImage" content="http://vertx.io/assets/favicons/vertx-favicon-7/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link href="http://fonts.googleapis.com/css?family=Ubuntu:400,500,700,400italic" rel="stylesheet" type="text/css">
  <link rel="alternate" type="application/rss+xml" title="RSS"
     href="http://vertx.io/feed.xml">
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-30144458-1', 'auto');
    ga('create', 'UA-71153120-1', 'auto', 'tracker');
    ga('send', 'pageview');
    ga('tracker.send', 'pageview');
  </script>
</head>
<body>

<a href="http://www.reactivemanifesto.org/" id="reactive-manifesto-banner">
  <img style="border: 0; position: fixed; right: 0; top:0; z-index: 9000"
    src="http://d379ifj7s9wntv.cloudfront.net/reactivemanifesto/images/ribbons/we-are-reactive-black-right.png">
</a>

<a id="skippy" class="sr-only sr-only-focusable" href="#content"><div class="container"><span class="skiplink-text">Skip to main content</span></div></a>

<header class="navbar navbar-default navbar-static-top" id="top" role="banner">
  <div class="container">
    <div class="navbar-header">
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#vertx-navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="http://vertx.io/" class="navbar-brand"><img alt="Brand" src="http://vertx.io/assets/logo-sm.png"></a>
    </div>
    <nav class="collapse navbar-collapse" id="vertx-navbar-collapse">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="http://vertx.io/download/">Download</a></li>
        <li><a href="http://vertx.io/docs/">Documentation</a></li>
        <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
        <li><a href="http://vertx.io/community/">Community</a></li>
        <li><a href="http://vertx.io/materials/">Materials</a></li>
        <li><a href="http://vertx.io/blog/">Blog</a></li>        
      </ul>
    </nav>
  </div>
</header>



  <div class="page-header" id="content">
    <div class="container">
      <div class="row">
        <div class="col-sm-12">
          <h1>Vert.x Circuit Breaker</h1>
          
        </div>
      </div>
    </div>
  </div>




<div id="content">
  <div class="container docs-content">
    <div class="row">
      <div class="col-sm-12 col-md-push-9 col-md-3 hidden-xs hidden-sm">
        <div id="sidebar" data-spy="affix">
          <ul class="sectlevel1">
<li><a href="#_vert_x_circuit_breaker">Vert.x Circuit Breaker</a></li>
<li><a href="#_using_the_vert_x_circuit_breaker">Using the vert.x circuit breaker</a></li>
<li><a href="#_using_the_circuit_breaker">Using the circuit breaker</a></li>
<li><a href="#_callbacks">Callbacks</a></li>
<li><a href="#_event_bus_notification">Event bus notification</a></li>
<li><a href="#_the_half_open_state">The half-open state</a></li>
<li><a href="#_using_netflix_hystrix">Using Netflix Hystrix</a></li>
</ul>
        </div>
      </div>
      <div class="col-sm-12 col-md-pull-3 col-md-9">
        <div class="toc hidden-md hidden-lg">
          <h2>Table of Contents</h2>
          <ul class="sectlevel1">
<li><a href="#_vert_x_circuit_breaker">Vert.x Circuit Breaker</a></li>
<li><a href="#_using_the_vert_x_circuit_breaker">Using the vert.x circuit breaker</a></li>
<li><a href="#_using_the_circuit_breaker">Using the circuit breaker</a></li>
<li><a href="#_callbacks">Callbacks</a></li>
<li><a href="#_event_bus_notification">Event bus notification</a></li>
<li><a href="#_the_half_open_state">The half-open state</a></li>
<li><a href="#_using_netflix_hystrix">Using Netflix Hystrix</a></li>
</ul>
        </div>
        <div class="sect1">
<h2 id="_vert_x_circuit_breaker">Vert.x Circuit Breaker</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Vert.x Circuit Breaker is an implementation of the Circuit Breaker <em>pattern</em> for Vert.x.</p>
</div>
<div class="paragraph">
<p>It keeps track of the
number of failures and <em>open the circuit</em> when a threshold is reached. Optionally, a fallback is executed.</p>
</div>
<div class="paragraph">
<p>Supported failures are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>failures reported by your code in a <code><a href="../../apidocs/io/vertx/core/Future.html">Future</a></code></p>
</li>
<li>
<p>exception thrown by your code</p>
</li>
<li>
<p>uncompleted futures (timeout)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Operations guarded by a circuit breaker are intended to by non-blocking and asynchronous in order to benefits from
the Vert.x execution model.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_using_the_vert_x_circuit_breaker">Using the vert.x circuit breaker</h2>
<div class="sectionbody">
<div class="paragraph">
<p>To use the Vert.x Circuit Breaker, add the following dependency to the <em>dependencies</em> section of your build
descriptor:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Maven (in your <code>pom.xml</code>):</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml">&lt;dependency&gt;
  &lt;groupId&gt;io.vertx&lt;/groupId&gt;
  &lt;artifactId&gt;vertx-circuit-breaker&lt;/artifactId&gt;
  &lt;version&gt;3.3.3&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Gradle (in your <code>build.gradle</code> file):</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">compile 'io.vertx:vertx-circuit-breaker:3.3.3'</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_using_the_circuit_breaker">Using the circuit breaker</h2>
<div class="sectionbody">
<div class="paragraph">
<p>To use the circuit breaker you need to:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Create a circuit breaker, with the configuration you want (timeout, number of failure before opening the circuit)</p>
</li>
<li>
<p>Execute some code using the breaker</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>Here is an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
    new CircuitBreakerOptions()
        .setMaxFailures(5) // number of failure before opening the circuit
        .setTimeout(2000) // consider a failure if the operation does not succeed in time
        .setFallbackOnFailure(true) // do we call the fallback on failure
        .setResetTimeout(10000) // time spent in open state before attempting to re-try
);

breaker.execute(future -&gt; {
  // some code executing with the breaker
  // the code reports failures or success on the given future.
  // if this future is marked as failed, the breaker increased the
  // number of failures
}).setHandler(ar -&gt; {
  // Get the operation result.
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The executed block receives a <code><a href="../../apidocs/io/vertx/core/Future.html">Future</a></code> object as parameter, to denote the
success or failure of the operation as well as the result. For example in the following example, the result is the
output of a REST endpoint invocation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
    new CircuitBreakerOptions().setMaxFailures(5).setTimeout(2000)
);

breaker.&lt;String&gt;execute(future -&gt; {
  vertx.createHttpClient().getNow(8080, "localhost", "/", response -&gt; {
    if (response.statusCode() != 200) {
      future.fail("HTTP error");
    } else {
      response
          .exceptionHandler(future::fail)
          .bodyHandler(buffer -&gt; {
            future.complete(buffer.toString());
          });
    }
  });
}).setHandler(ar -&gt; {
  // Do something with the result
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The result of the operation is provided using the:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>returned <code><a href="../../apidocs/io/vertx/core/Future.html">Future</a></code> when calling <code>execute</code> methods</p>
</li>
<li>
<p>provided <code><a href="../../apidocs/io/vertx/core/Future.html">Future</a></code> when calling the <code>executeAndReport</code> methods</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Optionally, you can provide a fallback executed when the circuit is open:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
    new CircuitBreakerOptions().setMaxFailures(5).setTimeout(2000)
);

breaker.executeWithFallback(
    future -&gt; {
      vertx.createHttpClient().getNow(8080, "localhost", "/", response -&gt; {
        if (response.statusCode() != 200) {
          future.fail("HTTP error");
        } else {
          response
              .exceptionHandler(future::fail)
              .bodyHandler(buffer -&gt; {
                future.complete(buffer.toString());
              });
        }
      });
    }, v -&gt; {
      // Executed when the circuit is opened
      return "Hello";
    })
    .setHandler(ar -&gt; {
      // Do something with the result
    });</code></pre>
</div>
</div>
<div class="paragraph">
<p>The fallback is called whenever the circuit is open, or if the
<code><a href="../../apidocs/io/vertx/circuitbreaker/CircuitBreakerOptions.html#isFallbackOnFailure--">isFallbackOnFailure</a></code> is enabled. When a fallback is
set, the result is using the output of the fallback function. The fallback function takes as parameter a
<code><a href="../../apidocs/java/lang/Throwable.html">Throwable</a></code> object and returned an object of the expected type.</p>
</div>
<div class="paragraph">
<p>The fallback can also be set on the <code><a href="../../apidocs/io/vertx/circuitbreaker/CircuitBreaker.html">CircuitBreaker</a></code> object directly:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
    new CircuitBreakerOptions().setMaxFailures(5).setTimeout(2000)
).fallback(v -&gt; {
  // Executed when the circuit is opened.
  return "hello";
});

breaker.execute(
    future -&gt; {
      vertx.createHttpClient().getNow(8080, "localhost", "/", response -&gt; {
        if (response.statusCode() != 200) {
          future.fail("HTTP error");
        } else {
          response
              .exceptionHandler(future::fail)
              .bodyHandler(buffer -&gt; {
                future.complete(buffer.toString());
              });
        }
      });
    });</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_callbacks">Callbacks</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You can also configures callbacks invoked when the circuit is opened or closed:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
    new CircuitBreakerOptions().setMaxFailures(5).setTimeout(2000)
).openHandler(v -&gt; {
  System.out.println("Circuit opened");
}).closeHandler(v -&gt; {
  System.out.println("Circuit closed");
});

breaker.execute(
    future -&gt; {
      vertx.createHttpClient().getNow(8080, "localhost", "/", response -&gt; {
        if (response.statusCode() != 200) {
          future.fail("HTTP error");
        } else {
          // Do something with the response
          future.complete();
        }
      });
    });</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also be notified when the circuit breaker decide to attempt to reset (half-open state). You can register
such as callback with <code><a href="../../apidocs/io/vertx/circuitbreaker/CircuitBreaker.html#halfOpenHandler-io.vertx.core.Handler-">halfOpenHandler</a></code>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_event_bus_notification">Event bus notification</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Every time the circuit state changes, an event is published on the event bus. The address on which the event are
sent is configurable with
<code><a href="../../apidocs/io/vertx/circuitbreaker/CircuitBreakerOptions.html#setNotificationAddress-java.lang.String-">setNotificationAddress</a></code>. If <code>null</code> is
passed to this method, the notifications are disabled. By default, the used address is <code>vertx.circuit-breaker</code>.</p>
</div>
<div class="paragraph">
<p>Each event contains a Json Object with:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>state</code> : the new circuit breaker state (<code>OPEN</code>, <code>CLOSED</code>, <code>HALF_OPEN</code>)</p>
</li>
<li>
<p><code>name</code> : the name of the circuit breaker</p>
</li>
<li>
<p><code>failures</code> : the number of failures</p>
</li>
<li>
<p><code>node</code> : the identifier of the node (<code>local</code> is Vert.x is not running in cluster mode)</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_the_half_open_state">The half-open state</h2>
<div class="sectionbody">
<div class="paragraph">
<p>When the circuit is “open,” calls to the circuit breaker fail immediately, without any attempt to execute the real
operation. After a suitable amount of time (configured from
<code><a href="../../apidocs/io/vertx/circuitbreaker/CircuitBreakerOptions.html#setResetTimeout-long-">setResetTimeout</a></code>, the circuit breaker decides that the
operation has a chance of succeeding, so it goes into the <code>half-open</code> state. In this state, the next call to the
circuit breaker is allowed to execute the dangerous operation. Should the call succeed, the circuit breaker resets
and returns to the <code>closed</code> state, ready for more routine operation. If this trial call fails, however, the circuit
breaker returns to the <code>open</code> state until another timeout elapses.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_using_netflix_hystrix">Using Netflix Hystrix</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://github.com/Netflix/Hystrix">Hystrix</a> provides an implementation of the circuit breaker pattern. You can use
Hystrix with Vert.x instead of this circuit breaker or in combination of. This section describes the tricks
to use Hystrix in a vert.x application.</p>
</div>
<div class="paragraph">
<p>First you would need to add the Hystrix dependency to your classpath or build descriptor. Refer to the Hystrix
page to details. Them, you need to isolate the "protected" call in a <code>Command</code>. Once you have your command, you
can execute it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">HystrixCommand&lt;String&gt; someCommand = getSomeCommandInstance();
String result = someCommand.execute();</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, the command execution is blocking, so have to call the command execution either in an <code>executeBlocking</code>
block or in a worker verticle:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">HystrixCommand&lt;String&gt; someCommand = getSomeCommandInstance();
vertx.&lt;String&gt;executeBlocking(
future -&gt; future.complete(someCommand.execute()),
ar -&gt; {
// back on the event loop
String result = ar.result();
}
);</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you use the async support of Hystrix, be careful that callbacks are not called in a vert.x thread and you have
to keep a reference on the context before the execution (with <code><a href="../../apidocs/io/vertx/core/Vertx.html#getOrCreateContext--">getOrCreateContext</a></code>,
and in the callback, switch back to the event loop using
<code><a href="../../apidocs/io/vertx/core/Vertx.html#runOnContext-io.vertx.core.Handler-">runOnContext</a></code>. Without this, you are loosing the Vert.x
concurrency model and have to manage the synchronization and ordering yourself:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">vertx.runOnContext(v -&gt; {
Context context = vertx.getOrCreateContext();
HystrixCommand&lt;String&gt; command = getSomeCommandInstance();
command.observe().subscribe(result -&gt; {
context.runOnContext(v2 -&gt; {
// Back on context (event loop or worker)
String r = result;
});
});
});</code></pre>
</div>
</div>
</div>
</div>

        

        
          <div id="footer">
            <div id="footer-text">
              
                Last updated 2016-09-12 08:38:06 CEST
              
              
            </div>
          </div>
        
      </div>
    </div>
  </div>
</div>

<footer>
  <div class="container">
    <div class="row">
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Vert.x</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/">Home</a></li>
          <li><a href="http://vertx.io/download/">Download</a></li>
          <li><a href="http://vertx.io/docs/">Documentation</a></li>
          <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
          <li><a href="http://vertx.io/blog/">Blog</a></li>
          <li><a href="http://vertx.io/vertx2/" class="vertx-2-link">Vert.x 2</a></li>
        </ul>
      </div>
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Community</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/community/">Help &amp; Contributors</a></li>
          <li><a href="http://vertx.io/materials/">Learning materials</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx">User Group</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx-dev">Developer Group</a></li>
        </ul>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-offset-2 col-md-6 copyright">
        <p>Vert.x is open source and dual licensed under the <a href="https://www.eclipse.org/org/documents/epl-v10.php">Eclipse Public License 1.0</a> and <a href="https://www.apache.org/licenses/LICENSE-2.0.html">Apache License 2.0</a>.</p>
        <p>This website is licensed under the <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0 License</a>.<br>
        Design by <a href="http://www.michel-kraemer.com">Michel Kr&auml;mer</a>. <a href="http://www.entypo.com">Entypo pictograms</a> by Daniel Bruce.</p>
        <div class="row">
          <div class="col-xs-12 col-lg-offset-1 col-md-5">
            <a href="http://eclipse.org">
            <img class="logo eclipse-logo" src="http://vertx.io/assets/eclipse_logo_grey_small.png" width="204" height="48">
            </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-0 col-md-5">
            <a href="http://cloudbees.com">
            <img class="logo cloudbees-logo" src="http://vertx.io/assets/Button-Built-on-CB-1-grey.png" width="180" height="48">
           </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-1 col-md-5 jprofiler">
            <a href="http://www.ej-technologies.com/products/jprofiler/overview.html"
            style="text-decoration:none">
            <img class="logo jprofiler-logo" src="http://vertx.io/assets/jprofiler-logo.png" width="48" height="48"><span class="jprofiler-logo">&nbsp; JPROFILER</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</footer>

<script src="http://static.jboss.org/theme/js/libs/jquery/jquery-1.9.1.min.js"></script>
<script src="http://vertx.io/javascripts/bootstrap.min.js"></script>
<script src="http://vertx.io/javascripts/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>



<script src="http://vertx.io/javascripts/sidebar.js"></script>


</body>
</html>
